<template>
  <a-modal
    destroy-on-close
    title="分享"
    :open="visible"
    :footer="null"
    width="670px"
    :body-style="{ padding: '24px 32px' }"
    centered
    @cancel="close()"
  >
    <div class="share-modal">
      <div class="header">
        <div class="header-left">
          <a-input v-model:value="fromState.user" v-trim class="w-286 mr-12" placeholder="请输入用户账号" />
          <a-checkbox-group v-model:value="fromState.role">
            <a-checkbox value="A" disabled>使用权限</a-checkbox>
            <a-checkbox value="B">管理权限</a-checkbox>
          </a-checkbox-group>
        </div>
        <a-button type="default" :loading="submitLoading" @click="submit">添加</a-button>
      </div>

      <div class="table-wrap mt-24">
        <a-table
          class="share-modal-table"
          :columns="tableColumns"
          :data-source="dataList"
          :pagination="false"
          row-key="id"
          @change="tableChange"
        />
        <!-- <div class="share-table-thead">
          <div class="share-table-row">
            <div class="share-table-cell">用户账号</div>
            <div class="share-table-cell">用户名</div>
            <div class="share-table-cell">权限</div>
            <div class="share-table-cell">授权时间</div>
            <div class="share-table-cell"></div>
          </div>
        </div> -->
        <div v-if="identifier !== 1" class="share-table-tbody">
          <div v-if="dataList?.length > 0">
            <div v-for="item in dataList" :key="item.userNum" class="share-table-row">
              <div class="share-table-cell" :title="item.tel">{{ item.tel }}</div>
              <div class="share-table-cell" :title="item.userName">{{ item.userName }}</div>
              <div class="share-table-cell" :title="roleMap[item.readOnly]">{{ roleMap[item.readOnly] }}</div>
              <div class="share-table-cell" :title="item.authTime">{{ item.authTime }}</div>
              <div class="share-table-cell">
                <a-button type="link" style="font-size: 12px" @click="remove(item)">移除</a-button>
              </div>
            </div>
          </div>
          <div v-else class="empty-img">
            <img src="@/assets/img/customer/empty.png" alt="empty" />
          </div>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
  import { message, Modal } from 'ant-design-vue'
  import { ref } from 'vue'

  import { filterTableColumns } from '@/utils/ant-component'

  interface ShareModalProps {
    fromState?: any
    pageForm?: any
    visible?: boolean
    getListApi: any
    submitApi?: any
    removeUserApi?: any
  }

  interface Params {
    id?: string
    [key: string]: any
  }

  const props = withDefaults(defineProps<ShareModalProps>(), {
    fromState: {},
    pageForm: {},
    visible: false
  })

  const emits = defineEmits<{
    (event: 'open'): void
    (event: 'close'): void
    (event: 'submit', fromState: any): void
  }>()

  const tableColumns = ref(
    filterTableColumns([
      {
        title: '用户账号',
        dataIndex: 'userNum',
        width: 120
      },
      {
        title: '用户名称',
        dataIndex: 'userName',
        width: 100
      },
      {
        title: '权限',
        dataIndex: 'role',
        width: 160
      },
      {
        title: '授权时间',
        isSort: true,
        dataIndex: 'authTime',
        width: 160
      },
      {
        dataIndex: 'tools',
        align: 'right',
        width: 58,
        ellipsis: false
      }
    ])
  )

  const visible = ref(props.visible || false)
  const identifier = ref<number>(1)
  let defaultParams: Params = {}
  const roleMap = ['使用权限', '使用权限，管理权限']

  const refreshList = () => {
    dataList.value = []
    pageForm.value.offset = 1
    identifier.value = Date.now()
    loadData()
  }
  const pageForm = ref({
    limit: 15,
    offset: 1,
    columns: 'authTime',
    order: 'desc',
    ...props.pageForm
  })
  const fromState = ref({
    user: '',
    role: ['A'],
    ...props.fromState
  })
  const resetForm = () => {
    ;(fromState.value = {
      user: '',
      role: ['A']
    }),
      (pageForm.value = {
        limit: 15,
        offset: 1,
        columns: 'authTime',
        order: 'desc'
      })
  }

  const dataList = ref<any[]>([])
  const open = (params?: Params) => {
    defaultParams = params || {}
    visible.value = true
    refreshList()
  }

  const close = () => {
    defaultParams = {}
    dataList.value = []
    visible.value = false
    resetForm()
  }

  const tableChange = (pagination: any, filters: any, sorter: any) => {
    pageForm.value.columns = sorter.field
    pageForm.value.order = sorter.order === 'ascend' ? 'asc' : 'desc'
    refreshList()
  }

  const remove = async (item: any) => {
    // 二次确认
    Modal.confirm({
      title: '移除后该用户的相关权限失效，请确认操作',
      centered: true,
      onOk: async () => {
        await props.removeUserApi?.({}, { urlParams: { id: item.id }, isAddUid: true })
        message.success('移除成功')
        refreshList()
      }
    })
  }

  const loadData = async () => {
    try {
      const { data } = await props.getListApi(
        {
          order: pageForm.value.order,
          columns: pageForm.value.columns
        },
        {
          urlParams: { id: defaultParams.id }
        }
      )
      dataList.value.push(...data)
      if (0 < pageForm.value.limit) {
        // $state.complete()
      } else {
        pageForm.value.offset++
        // $state.loaded()
      }
    } catch (error) {
      // $state.error()
    }
  }

  const submitLoading = ref(false)
  const submit = async () => {
    const params = {
      relId: defaultParams.id,
      tel: fromState.value.user,
      readOnly: fromState.value.role.length === 1 ? 0 : 1
    }
    if (!fromState.value.user) {
      message.warning('请输入用户账号')
      return
    }
    try {
      submitLoading.value = true
      await props.submitApi(params, { isAddUid: true, headers: { 'hide-message': 'true' } })
      emits('submit', fromState.value)
      message.success('操作成功')
      resetForm()
      refreshList()
    } catch (error: any) {
      Modal.warning({
        title: error?.message || '添加失败',
        centered: true,
        okButtonProps: {
          type: 'default'
        }
      })
    } finally {
      submitLoading.value = false
    }
  }

  defineExpose({
    open: open,
    close: close
  })
</script>

<style lang="less" scoped>
  .share-modal {
    width: 100%;

    .header {
      display: flex;
      justify-content: space-between;
      padding: 12px 16px;
      width: 100%;
      background: #f5f5f5;
      border: 1px solid #d9d9db;
      border-radius: 6px;

      .header-left {
        flex: 1;
      }
    }
  }

  .share-modal-table {
    :deep(.ant-table) {
      // height: 422px;
      border: none !important;
      border-radius: 0 !important;

      .ant-table-thead {
        tr > th {
          padding: 0 12px;
          height: 36px;
        }
      }

      .ant-table-tbody {
        display: none;

        tr > td {
          padding: 0 12px;
          height: 36px;
          border: none !important;
        }
      }
    }
  }

  .table-wrap {
    overflow: hidden;
    width: 596px;
    height: 422px;
    background: #fff;
    border: 1px solid #d9d9db;
    border-radius: 6px;
    border-top-left-radius: none;
    border-top-right-radius: none;

    .share-table-cell {
      padding: 0 12px;
      height: 36px;
      line-height: 36px;
      .elliptical-1();

      &:nth-child(1) {
        width: 120px;
      }

      &:nth-child(2) {
        width: 100px;
      }

      &:nth-child(3) {
        width: 160px;
      }

      &:nth-child(4) {
        width: 160px;
      }

      &:nth-child(5) {
        padding-right: 20px;
        padding-left: 0;
        width: 58px;
        text-align: right;
        text-overflow: clip;
      }
    }

    .share-table-thead {
      width: 100%;
      height: 36px;
      border-bottom: 1px solid #e8e8eb;
      background: #fafafa;

      .share-table-row {
        display: flex;
      }

      .share-table-cell {
        font-size: 14px;
        font-family: 'Noto Sans SC';
        color: rgba(17, 22, 31, 0.52);
        font-weight: 700;
      }
    }

    .share-table-tbody {
      overflow: auto;
      height: calc(100% - 36px);

      .share-table-row {
        display: flex;
      }

      .share-table-cell {
        font-size: 14px;
        color: rgba(16, 16, 20, 0.95);
        font-weight: 400;
      }

      .empty-img {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;
        flex-direction: column;
      }
    }
  }
</style>
